// 我的-部门管理-投递信息管理？
const baseUrl = 'https://gsdse.cn/api/KJRecruit';
const db = wx.cloud.database()
const _ = db.command
Page({
  //=======================================================================================
  /**
   * 页面的初始数据s
   */
  data: {
    //查看的年份数据的开始时间戳
    lookStartTimeStamp: "",
    //查看的年份数据的结束时间戳
    lookEndTimeStamp: "",
    time: [2024, 2025, 2026, 2027 , 2028 ,2029],
    index: '', //时间选定的数组索引
    departmentName: "网络研发部",
    departmentId: '',
    postTime: 2024, //选择的时间
    usersForm: [], //用户的信息
    showUsers: [], //已显示的用户信息
    isShowSearchBox: false, //是否展示搜索框
    inputValue: '',
    category: 1, //搜索内容
    /* 对象内容：
        userName:顾名思义
        departmentId:判断是否录取的条件，非空则为被录取
    */
    realName: "", //搜索的用户名,
    _openID_fileID_ObjArray: [],
    pages: 0,
    numbers: 9,
    // isamit:false//,
    tipsWithoutData: '投递信息正在加载中...',
    failCount: 0,
    webviewUrl:''
  },

  // =======================================================================================

  //封装函数


  //======================================
  //点击操作函数
  //======================================
  //点击报名表后跳转详细
  _viewItem(e) {
    console.log(e);
    wx.navigateTo({
      url: '../checkItemapplication/checkItemapplication?userId=' + e.currentTarget.dataset.userid + '&departmentName=' + this.data.departmentName,
    })
  },

  _chooseTime(e) {
    //获取时间戳
    const time = this.data.time
    this._showLoading()
    this.setData({
      index: e.detail.value,
      postTime: time[e.detail.value],
      lookStartTimeStamp: this.getYearTimeStamp(this.data.time[e.detail.value], 1, 1, 0, 0, 0),
      lookEndTimeStamp: this.getYearTimeStamp(this.data.time[e.detail.value], 12, 31, 23, 59, 59),
      usersForm: []
    })
    this._querryApplicationID();
    this._hideLoading()
  },

  getDate() {
    let that = this;
    wx.showLoading({
      title: '计算数据中',
    })
    var date = new Date();
    var Y = date.getFullYear();
    // console.log(Y);
    // console.log('今年是', Y, '年')

    this.setData({
      postTime: Y,
      lookStartTimeStamp: this.getYearTimeStamp(Y, 1, 1, 0, 0, 0),
      lookEndTimeStamp: this.getYearTimeStamp(Y, 12, 31, 23, 59, 59)
    });
  },

  //获取年份时间戳
  getYearTimeStamp(year, month, date, hours, minute, seconds) {
    var specificDate = new Date();
    specificDate.setFullYear(year);
    specificDate.setMonth(month - 1); // 月份是从 0 开始的，所以 11 表示 12 月
    specificDate.setDate(date);
    specificDate.setHours(hours);
    specificDate.setMinutes(minute);
    specificDate.setSeconds(seconds);
    return specificDate.getTime();
  },

  //下载报名表（完全不可用）
  cleanNoadmitted() {
    const that = this
    wx.showModal({
      title: '提示',
      content: '本操作将会下载已显示的所有报名表，请确认',
      showCancel: true,
      confirmColor: '#f38274',
      success: async (res) => {
        if (res.confirm) {
          console.log('用户点击确定')
          //判断系统型号
          const systemInfo = wx.getDeviceInfo().system
          // if (that.isMobileOperatingSystem(systemInfo)) {
          //   getApp().showMessage("由于微信限制，本功能只支持在PC端使用。")
          //   return;
          // }
          //下载文件
          const userArray = that.data.showUsers
          userArray.forEach((item) => {
            this.setData({
              webviewUrl: item.pdfUrl  // 替换为实际的下载页面地址
            });
          })

          // that.downloadFiles({
          //   urls: urlArray,
          //   success: function (res) {
          //     // console.dir(res);
          //     // console.info(res.get(url2).savedFilePath)
          //   },
          //   fail: function (e) {
          //     console.info("下载失败");
          //   }
          // })
          // wx.showModal({
          //   title: '提示',
          //   content: '下载结束！' + (that.data.failCount) + '个文件下载失败！',
          // })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //下载单个文件
  downloadFile(obj) {
    const that = this
    let success = obj.success;
    let fail = obj.fail;
    let url = obj.url;
    let id = "";
    if (obj.id) {
      id = obj.id;
    } else {
      id = url;
    }

    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url: obj.url,
        success: (res) => {
          wx.saveFile({
            tempFilePath: res.tempFilePath,
            success: function (result) {
              result.id = id;
              if (success) {
                success(result);
              }
            },
            fail: function (e) {
              console.info("保存一个文件失败");
              if (fail) {
                fail(e);
              }
            }
          })
        },
        fail: function (e) {
          console.info("保存一个文件失败");
          if (fail) {
            fail(e);
          }
        }
      })
    })
  },
  //下载全部文件
  downloadFiles(obj) {
    const that = this
    let success = obj.success; //下载成功
    let fail = obj.fail; //下载失败
    let urls = obj.urls; //下载地址 数组，支持多个 url下载 [url1,url2]
    let savedFilePaths = new Map();
    let urlsLength = urls.length; // 有几个url需要下载

    for (let i = 0; i < urlsLength; i++) {
      that.downloadFile({
        url: urls[i],
        success: function (res) {
          console.dir(res);
          //一个文件下载保存成功
          let savedFilePath = res.savedFilePath;
          savedFilePaths.set(res.id, res);
          console.info("savedFilePath:%s", savedFilePath);
          if (savedFilePaths.size == urlsLength) { //如果所有的url 才算成功
            if (success) {
              success(savedFilePaths)
            }
          }
        },
        fail: function (e) {
          console.info("下载失败");
          if (fail) {
            fail(e);
          }
        }
      })
    }
  },
  //判断操作系统是不是手机
  isMobileOperatingSystem(osString) {
    // 将操作系统字符串转换为小写，以便进行不区分大小写的比较  
    const lowerOsString = osString.toLowerCase();

    // 常见的移动操作系统名称，包括鸿蒙  
    const mobileOSNames = ['ios', 'android', 'windows phone', 'blackberry', 'symbian', 'harmonyos', '鸿蒙'];

    // 检查操作系统字符串是否包含任何移动操作系统名称  
    return mobileOSNames.some(name => lowerOsString.includes(name));
  },

  _showLoading() {
    wx.showLoading({
      title: '加载中',
      mask: 'false'
    })
  },

  _hideLoading() {
    setTimeout(() => {
      wx.hideLoading({
        success: (res) => {},
      })
    }, 1000);


  },
  _navigateTosearch() {
    this.setData({
      isShowSearchBox: true,
    })
  },

  async _querryApplicationID() {
    //当载入页面时，navigate跳转时携带该部门的值，然后使用云函数进行查表，然后保存在applicationList表中，使用列表渲染进行渲染
    //先获取报这个部门的用户的ID
    // //console.log(getApp().data)
    const departmentInfoArray = await this.selectApplyByWilling(getApp().data.department.departmentId)
    // console.log(departmentInfoArray)
    const usersForm = []
    for (let i = 0; departmentInfoArray != null && i < departmentInfoArray.length; i++) {
      const userInfo = await this.selectUser(departmentInfoArray[i].userId)
      userInfo.tag = departmentInfoArray[i].firstWilling == this.data.departmentId ? "firstStatus" : "secondStatus"

      //console.log(this.data.departmentId)
      userInfo.firstStatus = departmentInfoArray[i].firstStatus;
      userInfo.secondStatus = departmentInfoArray[i].secondStatus;
      userInfo.time = departmentInfoArray[i].time;
      userInfo.pdfUrl = departmentInfoArray[i].pdfUrl;
      usersForm.push(userInfo)
    }
    // console.log(usersForm) 
    //最后渲染数据
    this.setData({
      usersForm: usersForm,
      showUsers: usersForm,
      tipsWithoutData: '暂时没有投递信息'
    })
  },

  //获取报对应部门的用户的ID
  selectApplyByWilling(departmentId) {
    const that = this;
    return new Promise((resolve, reject) => {
      wx.request({
        url: baseUrl + '/selectApplyByWilling',
        method: 'POST',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
          departmentId: departmentId,
          startTime: that.data.lookStartTimeStamp,
          endTime: that.data.lookEndTimeStamp
        },
        success: function (res) {
          resolve(res.data.data)
        }
      })
    })
  },

  //获取用户的姓名和所属部门
  selectUser(userId) {
    const that = this;
    return new Promise((resolve, reject) => {
      // console.log(userId)
      wx.request({
        url: baseUrl + '/selectUser',
        method: 'POST',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
          userId: userId,

        },
        success: function (res) {
          //console.log(res.data.data)
          if (res.data.code != 1) {
            resolve({
              avatarUrl: res.data.data.avatarUrl,
              userName: res.data.data.userName,
              departmentId: res.data.data.departmentId,
              userId: userId
            })
          } else {
            console.log(res.data)
            resolve({})
          }
        }
      })
    })
  },

  handleInput(e) {
    this.setData({
      inputValue: e.detail.value,
    });
  },

  handleCategoryChange(e) {
    this.setData({
      category: parseInt(e.detail.value),
    });
  },

  //确认搜索
  confirmSearch() {
    //获取数据
    const userForm = this.data.usersForm
    const inputValue = this.data.inputValue
    const category = this.data.category
    var showForm = []

    userForm.forEach((item, index) => {
      var context = false;
      var status = false;
      //判断输入内容
      if (item.userName === inputValue || inputValue == '') {
        context = true
      }
      //判断选择状态
      const willStatus = (userForm[index][userForm[index].tag] === null) ? 2 : (userForm[index][userForm[index].tag] == 1) ? 4 : 3
      if (category == 1 || category == willStatus) {
        status = true
      }
      //最后总结
      if (context && status) {
        showForm.push(item)
      }
    })
    //注入数据
    console.log(showForm)
    this.setData({
      showUsers: showForm,
      //还原内容
      inputValue: '',
      category: 1
    })
    console.log("showUsers", this.data.showUsers)
    //关闭搜索
    this.setData({
      isShowSearchBox: false,
    })
  },
  //===============================
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    // console.log(options); 
    //把标题改成部门名称
    var departmentArray = ['秘书处', '网络研发部', "影视部", '动画部', "PC技术部", "新媒体运营部", 'UI设计部']
    var departmentName = departmentArray[options.departmentId - 1]
    if (departmentName != 'undefined') {
      this.setData({
        departmentName: departmentName,
        departmentId: options.departmentId,
      })
    }
    this.getDate();
    this._showLoading();
    this._hideLoading();
    await this._querryApplicationID()
  },
})